import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QMessageBox, QStackedWidget,
                             QGroupBox, QFormLayout, QDialog, QTabWidget, QTableWidget,
                             QTableWidgetItem, QHeaderView, QComboBox, QTextEdit, QGridLayout,
                             QSpinBox, QRadioButton, QButtonGroup)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database
from iteration1_dormitory_management.create_dormitory import DormitoryCreator
from iteration1_dormitory_management.query_dormitory import DormitoryQuery
from iteration1_dormitory_management.delete_dormitory import DormitoryDeleter
from iteration1_dormitory_management.update_dormitory import DormitoryUpdater

# 宿舍创建窗口
class CreateDormitoryDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('新建宿舍')
        self.setGeometry(300, 300, 400, 250)
        self.creator = DormitoryCreator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        self.building_input = QLineEdit()
        self.building_input.setPlaceholderText('例如: A, B, C...')
        form_layout.addRow('宿舍楼号:', self.building_input)
        
        self.room_input = QLineEdit()
        self.room_input.setPlaceholderText('例如: 101, 102...')
        form_layout.addRow('房间号:', self.room_input)
        
        self.capacity_input = QSpinBox()
        self.capacity_input.setRange(1, 10)
        self.capacity_input.setValue(4)
        form_layout.addRow('容纳人数:', self.capacity_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('宿舍信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.create_button = QPushButton('创建')
        self.create_button.clicked.connect(self.create_dormitory)
        button_layout.addWidget(self.create_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def create_dormitory(self):
        building = self.building_input.text().strip()
        room_number = self.room_input.text().strip()
        capacity = self.capacity_input.value()
        
        if not building or not room_number:
            QMessageBox.warning(self, '警告', '宿舍楼号和房间号不能为空')
            return
        
        result = self.creator.create_dormitory(building, room_number, capacity)
        
        if result:
            QMessageBox.information(self, '成功', f'宿舍 {building}-{room_number} 创建成功')
            self.accept()

# 宿舍查询窗口
class QueryDormitoryWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.query = DormitoryQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询选项
        option_group = QGroupBox('查询选项')
        option_layout = QVBoxLayout()
        
        self.query_all_btn = QRadioButton('查询所有宿舍')
        self.query_all_btn.setChecked(True)
        option_layout.addWidget(self.query_all_btn)
        
        self.query_by_building_room_btn = QRadioButton('根据楼号和房间号查询')
        option_layout.addWidget(self.query_by_building_room_btn)
        
        self.query_available_btn = QRadioButton('查询可用宿舍')
        option_layout.addWidget(self.query_available_btn)
        
        # 创建按钮组
        self.query_button_group = QButtonGroup()
        self.query_button_group.addButton(self.query_all_btn, 1)
        self.query_button_group.addButton(self.query_by_building_room_btn, 2)
        self.query_button_group.addButton(self.query_available_btn, 3)
        
        option_group.setLayout(option_layout)
        layout.addWidget(option_group)
        
        # 查询参数表单
        self.param_group = QGroupBox('查询参数')
        self.param_layout = QFormLayout()
        
        self.building_input = QLineEdit()
        self.building_input.setPlaceholderText('例如: A, B, C...')
        self.param_layout.addRow('宿舍楼号:', self.building_input)
        
        self.room_input = QLineEdit()
        self.room_input.setPlaceholderText('例如: 101, 102...')
        self.param_layout.addRow('房间号:', self.room_input)
        
        self.param_group.setLayout(self.param_layout)
        self.param_group.setVisible(False)
        layout.addWidget(self.param_group)
        
        # 查询按钮
        self.query_btn = QPushButton('查询')
        self.query_btn.clicked.connect(self.perform_query)
        layout.addWidget(self.query_btn)
        
        # 结果表格
        self.result_table = QTableWidget()
        self.result_table.setColumnCount(6)
        self.result_table.setHorizontalHeaderLabels(['宿舍ID', '楼号', '房间号', '容量', '当前人数', '状态'])
        self.result_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.result_table)
        
        # 连接信号
        self.query_button_group.buttonClicked.connect(self.on_query_option_changed)
        
        self.setLayout(layout)
    
    def on_query_option_changed(self, button):
        self.param_group.setVisible(button == self.query_by_building_room_btn)
    
    def perform_query(self):
        selected_option = self.query_button_group.checkedId()
        
        if selected_option == 1:  # 查询所有宿舍
            dormitories = self.query.query_all_dormitories()
            self.display_results(dormitories)
        
        elif selected_option == 2:  # 根据楼号和房间号查询
            building = self.building_input.text().strip()
            room_number = self.room_input.text().strip()
            
            if not building or not room_number:
                QMessageBox.warning(self, '警告', '宿舍楼号和房间号不能为空')
                return
            
            dormitory = self.query.query_dormitory_by_building_room(building, room_number)
            
            if dormitory:
                self.display_results([dormitory])
            else:
                self.result_table.setRowCount(0)
                QMessageBox.information(self, '提示', f'没有找到宿舍 {building}-{room_number} 的信息')
        
        elif selected_option == 3:  # 查询可用宿舍
            dormitories = self.query.query_available_dormitories()
            self.display_results(dormitories)
    
    def display_results(self, dormitories):
        if not dormitories:
            self.result_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何宿舍信息')
            return
        
        self.result_table.setRowCount(len(dormitories))
        
        for row, dorm in enumerate(dormitories):
            self.result_table.setItem(row, 0, QTableWidgetItem(str(dorm[0])))
            self.result_table.setItem(row, 1, QTableWidgetItem(dorm[1]))
            self.result_table.setItem(row, 2, QTableWidgetItem(dorm[2]))
            self.result_table.setItem(row, 3, QTableWidgetItem(str(dorm[3])))
            self.result_table.setItem(row, 4, QTableWidgetItem(str(dorm[4])))
            self.result_table.setItem(row, 5, QTableWidgetItem(dorm[5]))

# 宿舍删除窗口
class DeleteDormitoryWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.deleter = DormitoryDeleter()
        self.query = DormitoryQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询所有宿舍
        self.refresh_btn = QPushButton('刷新宿舍列表')
        self.refresh_btn.clicked.connect(self.refresh_dormitory_list)
        layout.addWidget(self.refresh_btn)
        
        # 宿舍列表
        self.dormitory_table = QTableWidget()
        self.dormitory_table.setColumnCount(6)
        self.dormitory_table.setHorizontalHeaderLabels(['宿舍ID', '楼号', '房间号', '容量', '当前人数', '状态'])
        self.dormitory_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.dormitory_table.setSelectionBehavior(QTableWidget.SelectRows)
        layout.addWidget(self.dormitory_table)
        
        # 删除按钮
        button_layout = QHBoxLayout()
        
        self.delete_single_btn = QPushButton('删除选中宿舍')
        self.delete_single_btn.clicked.connect(self.delete_selected_dormitory)
        button_layout.addWidget(self.delete_single_btn)
        
        self.delete_batch_btn = QPushButton('批量删除选中宿舍')
        self.delete_batch_btn.clicked.connect(self.batch_delete_dormitories)
        button_layout.addWidget(self.delete_batch_btn)
        
        layout.addLayout(button_layout)
        
        self.setLayout(layout)
        
        # 初始加载宿舍列表
        self.refresh_dormitory_list()
    
    def refresh_dormitory_list(self):
        dormitories = self.query.query_all_dormitories()
        
        if not dormitories:
            self.dormitory_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何宿舍信息')
            return
        
        self.dormitory_table.setRowCount(len(dormitories))
        
        for row, dorm in enumerate(dormitories):
            self.dormitory_table.setItem(row, 0, QTableWidgetItem(str(dorm[0])))
            self.dormitory_table.setItem(row, 1, QTableWidgetItem(dorm[1]))
            self.dormitory_table.setItem(row, 2, QTableWidgetItem(dorm[2]))
            self.dormitory_table.setItem(row, 3, QTableWidgetItem(str(dorm[3])))
            self.dormitory_table.setItem(row, 4, QTableWidgetItem(str(dorm[4])))
            self.dormitory_table.setItem(row, 5, QTableWidgetItem(dorm[5]))
    
    def delete_selected_dormitory(self):
        selected_rows = self.dormitory_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要删除的宿舍')
            return
        
        row = selected_rows[0].row()
        building = self.dormitory_table.item(row, 1).text()
        room_number = self.dormitory_table.item(row, 2).text()
        
        reply = QMessageBox.question(self, '确认删除', 
                                    f'确定要删除宿舍 {building}-{room_number} 吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            result = self.deleter.delete_dormitory(building, room_number)
            
            if result:
                QMessageBox.information(self, '成功', f'宿舍 {building}-{room_number} 已删除')
                self.refresh_dormitory_list()
    
    def batch_delete_dormitories(self):
        selected_rows = self.dormitory_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要删除的宿舍')
            return
        
        dormitory_ids = []
        dormitory_names = []
        
        for model_index in selected_rows:
            row = model_index.row()
            dormitory_id = int(self.dormitory_table.item(row, 0).text())
            building = self.dormitory_table.item(row, 1).text()
            room_number = self.dormitory_table.item(row, 2).text()
            dormitory_ids.append(dormitory_id)
            dormitory_names.append(f"{building}-{room_number}")
        
        reply = QMessageBox.question(self, '确认批量删除', 
                                    f'确定要删除选中的 {len(dormitory_ids)} 个宿舍吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            success_count, total_count = self.deleter.delete_dormitories(dormitory_ids)
            QMessageBox.information(self, '成功', f'批量删除完成：成功 {success_count}/{total_count}')
            self.refresh_dormitory_list()

# 宿舍更新窗口
class UpdateDormitoryWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.updater = DormitoryUpdater()
        self.query = DormitoryQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询所有宿舍
        self.refresh_btn = QPushButton('刷新宿舍列表')
        self.refresh_btn.clicked.connect(self.refresh_dormitory_list)
        layout.addWidget(self.refresh_btn)
        
        # 宿舍列表
        self.dormitory_table = QTableWidget()
        self.dormitory_table.setColumnCount(6)
        self.dormitory_table.setHorizontalHeaderLabels(['宿舍ID', '楼号', '房间号', '容量', '当前人数', '状态'])
        self.dormitory_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.dormitory_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.dormitory_table.itemSelectionChanged.connect(self.on_selection_changed)
        layout.addWidget(self.dormitory_table)
        
        # 更新表单
        self.update_group = QGroupBox('更新宿舍信息')
        update_layout = QFormLayout()
        
        self.capacity_input = QSpinBox()
        self.capacity_input.setRange(1, 10)
        self.capacity_input.setValue(4)
        update_layout.addRow('新容量:', self.capacity_input)
        
        # 状态选择
        self.status_combo = QComboBox()
        self.status_combo.addItem('可用', 'available')
        self.status_combo.addItem('不可用', 'unavailable')
        self.status_combo.addItem('维护中', 'maintenance')
        update_layout.addRow('新状态:', self.status_combo)
        
        self.update_group.setLayout(update_layout)
        layout.addWidget(self.update_group)
        
        # 更新按钮
        self.update_btn = QPushButton('更新宿舍信息')
        self.update_btn.clicked.connect(self.update_dormitory)
        self.update_btn.setEnabled(False)
        layout.addWidget(self.update_btn)
        
        self.setLayout(layout)
        
        # 初始加载宿舍列表
        self.refresh_dormitory_list()
    
    def refresh_dormitory_list(self):
        dormitories = self.query.query_all_dormitories()
        
        if not dormitories:
            self.dormitory_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何宿舍信息')
            return
        
        self.dormitory_table.setRowCount(len(dormitories))
        
        for row, dorm in enumerate(dormitories):
            self.dormitory_table.setItem(row, 0, QTableWidgetItem(str(dorm[0])))
            self.dormitory_table.setItem(row, 1, QTableWidgetItem(dorm[1]))
            self.dormitory_table.setItem(row, 2, QTableWidgetItem(dorm[2]))
            self.dormitory_table.setItem(row, 3, QTableWidgetItem(str(dorm[3])))
            self.dormitory_table.setItem(row, 4, QTableWidgetItem(str(dorm[4])))
            self.dormitory_table.setItem(row, 5, QTableWidgetItem(dorm[5]))
    
    def on_selection_changed(self):
        selected_rows = self.dormitory_table.selectionModel().selectedRows()
        self.update_btn.setEnabled(len(selected_rows) > 0)
    
    def update_dormitory(self):
        selected_rows = self.dormitory_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要更新的宿舍')
            return
        
        row = selected_rows[0].row()
        dormitory_id = int(self.dormitory_table.item(row, 0).text())
        building = self.dormitory_table.item(row, 1).text()
        room_number = self.dormitory_table.item(row, 2).text()
        
        capacity = self.capacity_input.value()
        status = self.status_combo.currentData()
        
        reply = QMessageBox.question(self, '确认更新', 
                                    f'确定要更新宿舍 {building}-{room_number} 的信息吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            result = self.updater.update_dormitory(dormitory_id, capacity, status)
            
            if result:
                QMessageBox.information(self, '成功', f'宿舍 {building}-{room_number} 信息已更新')
                self.refresh_dormitory_list()

# 批量创建宿舍窗口
class BatchCreateDormitoryDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('批量新建宿舍')
        self.setGeometry(300, 300, 500, 400)
        self.creator = DormitoryCreator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 说明标签
        instruction_label = QLabel('每行输入一个宿舍信息，格式：楼号,房间号,容纳人数')
        instruction_label.setWordWrap(True)
        layout.addWidget(instruction_label)
        
        # 文本输入区域
        self.text_input = QTextEdit()
        self.text_input.setPlaceholderText('例如:\nA,101,4\nA,102,4\nB,201,6')
        layout.addWidget(self.text_input)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.create_button = QPushButton('批量创建')
        self.create_button.clicked.connect(self.batch_create_dormitories)
        button_layout.addWidget(self.create_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def batch_create_dormitories(self):
        text = self.text_input.toPlainText().strip()
        if not text:
            QMessageBox.warning(self, '警告', '请输入宿舍信息')
            return
        
        lines = text.split('\n')
        dormitories_data = []
        
        for line in lines:
            parts = [part.strip() for part in line.split(',')]
            if len(parts) < 3:
                QMessageBox.warning(self, '警告', f'格式错误: {line}\n请确保包含楼号、房间号和容纳人数')
                return
            
            building = parts[0]
            room_number = parts[1]
            capacity = parts[2]
            
            dormitories_data.append((building, room_number, capacity))
        
        if dormitories_data:
            success_count, total_count = self.creator.batch_create_dormitories(dormitories_data)
            QMessageBox.information(self, '成功', f'批量创建完成：成功 {success_count}/{total_count}')
            self.accept()

# 宿舍管理主窗口
class DormitoryManagementWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('宿舍信息管理')
        self.setGeometry(100, 100, 800, 600)
        self.initUI()
        
    def initUI(self):
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建选项卡窗口
        tab_widget = QTabWidget()
        
        # 创建宿舍信息管理的各个功能选项卡
        self.create_tab = QWidget()
        self.query_tab = QueryDormitoryWidget()
        self.delete_tab = DeleteDormitoryWidget()
        self.update_tab = UpdateDormitoryWidget()
        
        # 设置创建宿舍选项卡
        create_layout = QVBoxLayout()
        create_btn = QPushButton('新建宿舍')
        create_btn.setMinimumHeight(50)
        create_btn.setFont(QFont('Arial', 12))
        create_btn.clicked.connect(self.open_create_dialog)
        create_layout.addWidget(create_btn)
        
        # 添加批量创建宿舍按钮
        batch_create_btn = QPushButton('批量新建宿舍')
        batch_create_btn.setMinimumHeight(50)
        batch_create_btn.setFont(QFont('Arial', 12))
        batch_create_btn.clicked.connect(self.open_batch_create_dialog)
        create_layout.addWidget(batch_create_btn)
        
        create_layout.addStretch()
        self.create_tab.setLayout(create_layout)
        
        # 添加选项卡
        tab_widget.addTab(self.create_tab, '新建宿舍')
        tab_widget.addTab(self.query_tab, '查询宿舍')
        tab_widget.addTab(self.delete_tab, '删除宿舍')
        tab_widget.addTab(self.update_tab, '更新宿舍信息')
        
        main_layout.addWidget(tab_widget)
        
        # 返回按钮
        back_btn = QPushButton('返回主菜单')
        back_btn.clicked.connect(self.close)
        main_layout.addWidget(back_btn)
    
    def open_create_dialog(self):
        dialog = CreateDormitoryDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果创建成功，刷新其他选项卡的数据
            self.query_tab.perform_query()
            self.delete_tab.refresh_dormitory_list()
            self.update_tab.refresh_dormitory_list()
            
    def open_batch_create_dialog(self):
        dialog = BatchCreateDormitoryDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果批量创建成功，刷新其他选项卡的数据
            self.query_tab.perform_query()
            self.delete_tab.refresh_dormitory_list()
            self.update_tab.refresh_dormitory_list()

# 如果直接运行此文件，提供测试界面
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DormitoryManagementWindow()
    window.show()
    sys.exit(app.exec_())